# -*- coding: UTF-8 -*-
# vim: expandtab sw=4 ts=4 sts=4
#
#     This file is part of IMAPylator
#
#    IMAPylator is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Foobar is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.

'''
    Replace "From:" header with "Sender:" header and delete "Sender:" 
    add a "X-IMAPylator-uploaded" header with UTC datetime
'''

import IMAPylatorMatch
from datetime import datetime

class FixOutlookHeaders(IMAPylatorMatch.IMAPylatorMatch):

    def matchFolder(self, folder, opt=None):
        '''
        folder name to check.
        example: -F Sent."Trash,Junk,Mail Spam" 
                return True if current folder name il "Sent"
                return false if current folder name is Trash or Junk or Mail Spam
        '''
        if opt:
            include = opt.split(".")[0].split(',')
            exclude = opt.split(".")[1].split(',')
            print exclude
        else:
            return True

        if folder in exclude:
            return False
        if folder in include or (len(include) == 1 and include[0] == ''):
            return True

        return False

    def match(self, headers, flags, internal_date, folder, opt=None):
        '''
        None
        '''
        
        if headers.has_key('Sender'):
            if headers['Sender'].count(headers['From']):
                return True

        return False

    def action(self, message, flags, folder, internal_date, opt=None):
        '''
        dry-run: not execute any action
        example: -A dry-run print a message abstract
        '''

        self.message = self._sanitize(message)
        self.flags = flags
        self.folder = folder
        self.internal_date = internal_date
        
        if opt == "dry-run":
            return "dunno"
        else:
            return "replace"
    
    def _sanitize(self, message):
        message.add_header("X-IMAPylator-uploaded", datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC"))
        message.replace_header("From", message['Sender'])
        #message.replace_header("From", '"Pablo Albani" <demo-pablo.albani@atos-servizi.it>')
        del(message['Sender'])

        return message


